<template>
  <div style="background: #f4f4f4;">
    <div style="margin: 0 auto; width: 60%;">
    <h2 style="font-size: larger">倒计时: {{timer}}</h2>
    </div>
    <div style="margin: 0 auto; width: 60%; padding: 25px">
      <div class="app-container">
        <h2>作业课程：{{formData.courseName}}</h2>
        <h3>{{ formData.taskName }} (满分：{{ formData.fullScore }})</h3>
        <el-form
            ref="ruleForm"
            :model="formData"
            :rules="rules"
            label-width="100px"
            class="demo-ruleForm"
        >
          <h4 v-if="formData.one.length>0">单选题({{ formData.taskOneScore }}分)</h4>
          <div v-for="item in formData.one">
            <span style="display: block">题目({{ item.totalScore }}分)：{{item.content}}</span>
            <span style="display: block; margin-top: 15px">A：{{item.options.split(",")[0]}}</span>
            <span style="display: block; margin-top: 5px">B：{{item.options.split(",")[1]}}</span>
            <span style="display: block; margin-top: 5px">C：{{item.options.split(",")[2]}}</span>
            <span style="display: block; margin-top: 5px">D：{{item.options.split(",")[3]}}</span>
            <span style="display: block; margin-top: 15px; margin-bottom: 25px"> 选项：
              <el-radio v-model="item.sa" label="A">A</el-radio>
              <el-radio v-model="item.sa" label="B">B</el-radio>
              <el-radio v-model="item.sa" label="C">C</el-radio>
              <el-radio v-model="item.sa" label="D">D</el-radio>
            </span>
          </div>

          <h4 v-if="formData.two.length>0">多选题({{ formData.taskTwoScore }}分)</h4>
          <div  v-for="item in formData.two">
            <span style="display: block">题目({{ item.totalScore }}分)：{{item.content}}</span>
            <span style="display: block; margin-top: 15px">A：{{item.options.split(",")[0]}}</span>
            <span style="display: block; margin-top: 5px">B：{{item.options.split(",")[1]}}</span>
            <span style="display: block; margin-top: 5px">C：{{item.options.split(",")[2]}}</span>
            <span style="display: block; margin-top: 5px">D：{{item.options.split(",")[3]}}</span>
            <span style="margin-top: 15px; margin-bottom: 25px"> 选项：
               <el-checkbox-group v-model="item.ma" >
                  <el-checkbox label="A">A</el-checkbox>
                  <el-checkbox label="B">B</el-checkbox>
                  <el-checkbox label="C">C</el-checkbox>
                  <el-checkbox label="D">D</el-checkbox>
                </el-checkbox-group>
            </span>
          </div>
          <h4 v-if="formData.three.length>0">判断选题({{ formData.taskThreeScore }}分)</h4>
          <div  v-for="item in formData.three">
            <span style="display: block">题目({{ item.totalScore }}分)：{{item.content}}</span>
            <span style="display: block; margin-top: 15px">A：{{item.options.split(",")[0]}}</span>
            <span style="display: block; margin-top: 5px">B：{{item.options.split(",")[1]}}</span>
            <span style="display: block; margin-top: 15px; margin-bottom: 25px"> 选项：
              <el-radio v-model="item.sa" label="正确">正确</el-radio>
              <el-radio v-model="item.sa" label="错误">错误</el-radio>
            </span>
          </div>

          <h4 v-if="formData.discussContext.length>0">主观题({{ formData.discussScore }}分)</h4>
          <div  v-for="item in formData.discussContext">
            <span style="display: block">题目({{ item.totalScore }}分)：{{item.content}}</span>
            <span style="display: block; margin-top: 15px; margin-bottom: 25px"> 答案：
              <el-input v-model="item.discussContextAnswer" type="textarea"></el-input>
            </span>
          </div>

          <el-form-item>
            <el-button style="margin-left: 200px;" type="primary" @click="submitForm()">提交</el-button>
            <el-button style="margin-left: 20px;" type="primary"  @click="retrunPage">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import store from '@/store'
import { getQuestion, addQuestionItem } from '@/api/student/workTaskStudent'

export default {
  name: "info",
  data() {
    return {
      timerOn: false,
      timer: '00:00:00',
      checkedData: [],
      headers: {
        Authorization: "Bearer " + store.getters.token,
      },
      taskId: "",
      formData: {
        id: '',
        one: [],
        two: [],
        three: [],
        taskOneScore: "",
        discussScore: "",
        taskTwoScore: "",
        taskThreeScore: "",
        fullScore: "",
        taskName: "",
        taskId: "",
        endTime: ""
      },
      rules: {},
      counter: 0,
      timerId: ''
    };
  },
  created() {
    this.taskId = this.$route.params.id
    this.getExamItem()
  },
  beforeDestroy() {
    clearInterval(this.timerId)
  },
  methods: {
    getExamItem() {
      console.log('this.formData.taskId',this.formData.taskId,this.$route.params.id)
      getQuestion({'taskId': this.$route.params.id}).then((res) => {
        this.formData = res.data
        this.startTimer()
      })
    },
    submitForm() {
      console.log(this.formData)
      // 单选题判断
      if (this.formData.one.length > 0) {
        this.formData.one.forEach(item => {
          console.log(item.sa)
          if (item.sa === null) {
            this.$message.warning("您有题未作答，请全部作答后在提交！")
            throw new Error("已找到，退出循环");
          }
        })
      }
      // 多选题
      if (this.formData.two.length > 0) {
        this.formData.two.forEach(item => {
          console.log(item.sa)
          if (item.ma.length === 0) {
            this.$message.warning("您有题未作答，请全部作答后在提交！")
            throw new Error("已找到，退出循环");
          }
        })
      }
      // 单选题判断
      if (this.formData.three.length > 0) {
        this.formData.three.forEach(item => {
          console.log(item.sa)
          if (item.sa === null) {
            this.$message.warning("您有题未作答，请全部作答后在提交！")
            throw new Error("已找到，退出循环");
          }
        })
      }
      // 主观
      if (this.formData.discussContext.length > 0) {
        this.formData.discussContext.forEach(item => {
          console.log(item.sa)
          if (item.discussContextAnswer === null) {
            this.$message.warning("您有题未作答，请全部作答后在提交！")
            throw new Error("已找到，退出循环");
          }
        })
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        console.log(this.formData)
        this.formData.taskId=this.taskId
        addQuestionItem(this.formData).then((response) => {
          this.$notify.success("交卷成功！");
          this.$router.push({path: "/s/homeworkOnLine"})
        });
      });
    },
    retrunPage() {
      this.$router.push({ name: 'homeworkOnLine'})
    },
    startTimer() {
      this.timer = this.getTimeDifference(this.formData.endTime)
      this.updateTime()
    },
    autoSubmit() {
      this.formData.taskId=this.taskId
      addQuestionItem(this.formData).then((response) => {
        this.$notify.success("交卷成功！");
        this.$router.push({path: "/s/homeworkOnLine"})
      })
    },
    updateTime() {
      this.timerId = setInterval(() => {
        console.log(this.timer)
        const parts = this.timer.split(':')
        let days = parseInt(parts[0], 10)
        let hours = parseInt(parts[1], 10)
        let minutes = parseInt(parts[2], 10)
        let seconds = parseInt(parts[3], 10)
        if (Date.parse(this.formData.endTime) - new Date() <= 0) {
          this.$message.warning('答题时间到,系统自动交卷')
          clearInterval(this.timerId)
          this.timer = '00:00:00'
          this.autoSubmit()
        }
        seconds--
        if(seconds==0 && minutes==1 && hours==0 && days==0){
          this.$message.warning('答题时间还有一分钟,请尽快交卷')
        }
        if (seconds <= 0) {
          if(minutes==0 && hours==0 && days==0){
            seconds = 0
          } else {
            seconds = 59
          }
          minutes--
          if (minutes <= 0) {
            if(hours==0 && days==0){
              minutes = 0
            }else{
              minutes = 59
            }
            hours--
            if (hours <= 0) {
              if (days == 0) {
                hours = 0
              } else {
                hours = 23
              }
              days--
              if (days <= 0) {
                days = 0
              }
            }
          }
        }
        this.timer = (days < 10 ? '0' + days : days) + ':' + (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
      }, 1000)
    },
    getTimeDifference(endDate) {
      // 计算距离结束时间的毫秒数
     // const currentDate = new Date()
      // 增加5秒
     // currentDate.setSeconds(currentDate.getSeconds() + 5)
     // console.log('currentDate', currentDate)
      // const diff = (currentDate - new Date()) / 1000
      const diff = (Date.parse(endDate) - new Date()) / 1000
      // 计算剩余的天、小时、分钟、秒数
      const days = Math.floor(diff / 86400)
      const hours = Math.floor((diff / 86400) % 24)
      const minutes = Math.floor(((diff % 86400) % 3600) / 60)
      const seconds = Math.floor(((diff % 86400) % 3600) % 60)
      console.log("days", days)
      console.log("hours",hours)
      console.log("minutes",hours)
      console.log("seconds",hours)
      return (days < 10 ? '0' + days : days) + ':' + (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
    }
  }
}
</script>
<style lang="scss">
</style>
